
import { addon } from "pao-aop";
import { reactControl, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { Button, Table, DatePicker, Modal, Form, Radio, TreeSelect } from "antd";
import { AppServiceUtility } from 'src/projects/app/appService';
import { MainContent } from "src/business/components/style-components/main-content";
import { MainCard } from "src/business/components/style-components/main-card";
// const { Option } = Select;
const { MonthPicker } = DatePicker;
import moment from 'moment';
import { request } from "src/business/util_tool";
import { exprot_excel } from "src/business/util_tool";
let columns_total: any = [
    {
        title: '结算月份',
        dataIndex: 'year_month',
        key: 'year_month',
        width: 150,
    },
    {
        title: '机构',
        dataIndex: 'service_provider_name',
        key: 'service_provider_name',
        width: 150,
    },
    // {
    //     title: '服务点',
    //     dataIndex: 'service_provider_adress',
    //     key: 'service_provider_adress',
    //     width: 100,
    // },
    {
        title: '订单数',
        dataIndex: 'order_quantity',
        key: 'order_quantity',
        width: 150,
    },
    {
        title: '总金额',
        dataIndex: 'valuation_amount_total',
        key: 'valuation_amount_total',
        width: 100,
    }
];

/** 状态：镇街结算组件数据 */
export interface OrderReportState extends ReactViewState {
    /** 合计数据 */
    dataTotalSource: any[];
    /** 日期条件 */
    query_month?: any;
    /** 控制弹框显示 */
    show?: any;
    /** 导出的条件 */
    select_type?: any;
    /** 服务商列表 */
    org_list: any[];
    /** 选择的服务商Id */
    org_id: string;
}
/** 组件：镇街结算组件视图 */
export class OrderReport extends React.Component<OrderReportControl, OrderReportState> {
    constructor(props: OrderReportControl) {
        super(props);
        this.state = {
            dataTotalSource: [],
            select_type: 1,
            show: false,
            query_month: moment().format('YYYY/MM'),
            org_list: [],
            org_id: ''
        };
    }
    // 导出类型选择
    onChangeRadio(value: any) {
        // 全部
        if (value === 1) {
            this.setState({
                select_type: value
            });
        }
        // 筛选记录进行导出
        if (value === 0) {
            this.setState({
                select_type: value
            });
        }
    }
    /** 导出按钮 */
    export = () => {
        this.setState({ show: true });
    }
    // 下载
    download() {
        // 判断导出选择的条件
        const { select_type } = this.state;
        // 全部
        if (select_type === 1) {
            let condition = { 'month': this.state.query_month };
            request(this, AppServiceUtility.service_record_service.get_order_report!(condition))!
                .then((data: any) => {
                    if (data['result']) {
                        let new_data: any = [];
                        data['result'].map((item: any) => {
                            new_data.push({
                                "结算月份": item.year_month,
                                "机构": item.service_provider_name,
                                "服务点": item.service_provider_adress,
                                "订单数": item.order_quantity,
                                "总金额": item.valuation_amount_total
                            });
                        });
                        exprot_excel([{ name: '订单统计（汇总）', value: new_data }], '订单统计（汇总）', 'xls');
                    }
                });
        }
        this.setState({ 'show': false });
    }
    // 显示/取消弹窗
    onCancel(data: any) {
        this.setState(data);
    }
    componentWillMount() {
        this.select_func({ 'month': moment().format('YYYY/MM') });
        // 查询服务商列表
        request(this, AppServiceUtility.person_org_manage_service.get_organization_tree_list!({ 'organization_type': '服务商' }))!
            .then((data: any) => {
                this.setState({
                    org_list: data!.result!
                });
            })
            .catch(err => {
                console.info(err);
            });
    }

    /**
     * 查询方法
     */
    private select_func = (condition: {}) => {
        request(this, AppServiceUtility.service_record_service.get_order_report!(condition))!
            .then((res: any) => {
                this.setState({
                    dataTotalSource: res.result
                });
            });
    }
    /** 日期范围回调 */
    time_change = (date: any, dateString: string) => {
        this.setState({
            query_month: dateString
        });
        let condition = { 'month': dateString };
        if (this.state.org_id) {
            condition['org_id'] = this.state.org_id;
        }
        this.select_func(condition);
    }
    /** 树形选择框改变事件 */
    onChangeTree = (value: any) => {
        this.setState({
            org_id: value
        });
        let condition = { 'month': this.state.query_month, 'org_id': value };
        this.select_func(condition);
    }
    render() {
        const { getFieldDecorator } = this.props.form!;
        return (
            <MainContent>
                <MainCard title='订单统计' style={{ position: 'relative' }}>
                    <div style={{ overflow: 'hidden', position: 'absolute', top: '13px', right: '25px' }}>
                        <Button type="primary" onClick={this.export} style={{ float: 'right', marginRight: '3px' }}>导出</Button>
                        {/* <Button type="primary" style={{ float: 'right', marginRight: '3px' }}>查询</Button> */}
                        <div style={{ float: 'right', marginRight: '3px' }}>
                            <MonthPicker onChange={this.time_change} defaultValue={moment(moment(), 'YYYY/MM')} format={'YYYY/MM'} />
                        </div>
                        <div style={{ float: 'right', marginRight: '140px' }}>
                            <TreeSelect
                                showSearch={true}
                                treeNodeFilterProp={'title'}
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                allowClear={true}
                                onChange={this.onChangeTree}
                                treeDefaultExpandAll={true}
                                treeData={this.state.org_list}
                                placeholder={"请选择服务商"}
                                style={{
                                    width: '12em'
                                }}
                            />
                        </div>
                    </div>
                    <Table columns={columns_total} dataSource={this.state.dataTotalSource} pagination={{ pageSize: 10 }} bordered={true} size="middle" />
                </MainCard>
                <Modal
                    title="请选择导出类型"
                    visible={this.state.show}
                    onOk={() => this.download()}
                    onCancel={() => this.onCancel({ show: !this.state.show })}
                    okText="下载"
                    cancelText="取消"
                >
                    <MainCard>
                        <Form>
                            <Form.Item>
                                {getFieldDecorator('isAll', {
                                })(
                                    <Radio.Group defaultValue={1} onChange={(e: any) => { this.onChangeRadio(e.target.value); }}>
                                        <Radio defaultChecked={true} key={1} value={1}>导出全部记录</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                        </Form>
                    </MainCard >
                </Modal>
            </MainContent>
        );
    }
}

/**
 * 控件：镇街结算组件控制器
 * @description 镇街结算组件
 * @author
 */
@addon('OrderReport', '镇街结算组件', '镇街结算组件')
@reactControl(Form.create<any>()(OrderReport), true)
export class OrderReportControl extends ReactViewControl {
}